<template>
<div>
  查看库存
  <el-form   :model="queryParams" ref="queryForm" size="small" :inline="true">
    <el-form-item label="产品名称" prop="">
      <el-input
        v-model="queryParams.productName"
        placeholder="请输入产品名称"
        clearable
        @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="分类名称" prop="categoryName">
      <el-cascader
        v-model="queryParams.categoryIds"
        :options="categoryTree"
        placeholder="请选择分类名称"
        clearable
        :props="{ checkStrictly: true, label: 'name', value: 'id' }"
        @change="handleCategoryChange"
      ></el-cascader>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
    </el-form-item>

    <el-button type="primary" icon="el-icon-search" size="mini" @click="openDrawer"  style="float: right;">查看视图</el-button>
  </el-form>

  <el-button  type="primary" @click="handleExport"   >导出数据</el-button>
<!-- v-hasPermi="['inventory:list:export']"  todo 导出数据-->

  <el-table v-loading="loading" :data="paoductsList" style="width: 100%">
    <el-table-column prop="inventoryId" label="库存id"></el-table-column>
    <el-table-column label="商品图片" width="120">
      <template slot-scope="scope">
        <el-image
          v-if="scope.row.productImage"
          :src="scope.row.productImage"
          fit="cover"
          :preview-src-list="[scope.row.productImage]"          style="width: 80px; height: 80px; border-radius: 4px;"
        >
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        <div v-else class="no-image">
          <i class="el-icon-picture-outline"></i>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
    <el-table-column prop="sku" label="商品SKU" width="180"></el-table-column>
    <el-table-column prop="categoryName" label="分类名称" width="180"></el-table-column>
    <el-table-column prop="quantity" label="库存总数量数量" width="180"></el-table-column>
    <el-table-column prop="availableQuantity" label="可用库存数量" width="180"></el-table-column>
    <el-table-column prop="lockedQuantity" label="锁定库存数量" width="180"></el-table-column>
    <el-table-column prop="status" label="上架状态" width="180">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.zzsz_product_status" :value="scope.row.status" />
      </template>
    </el-table-column>
    <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
      <template slot-scope="scope">
        <span>{{ parseTime(scope.row.updatedAt) }}</span>
      </template>
    </el-table-column>

  </el-table>
  <pagination
    v-show="total>0"
    :total="total"
    :page.sync="queryParams.pageNum"
    :limit.sync="queryParams.pageSize"
    @pagination="getlist"
  />


  <el-drawer
    title="查看视图"
    :visible.sync="drawer"
    :direction="direction"
    :before-close="handleClose"
    size="40%"
    >
    <!-- 图表容器：使用flex布局排列 -->
    <div style="display: flex; flex-wrap: wrap; gap: 20px;">
      <!-- 分类商品数量饼图 -->
      <div ref="categoryCountChart" style="width: 700px; height: 400px;"></div>
      <!-- 分类商品占比饼图 -->
      <div ref="categoryRatioChart" style="width: 700px; height: 400px;"></div>
      <!-- 分类库存折线图 -->
      <div ref="categoryInventoryChart" style="width: 100%; height: 500px;"></div>
    </div>
  </el-drawer>



</div>
</template>

<script>
import { getlist ,getCategoryName, exportList} from '@/api/inventory/list'
import * as echarts from 'echarts'
export default {
  name: "",
  dicts:['zzsz_product_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 商品列表
      paoductsList:[],
      //搜索参数
      queryParams: {
        productName: "",
        categoryIds: []  ,// 级联选择器需要数组类型v-model
        pageNum: 1,
        pageSize: 10,
      },
      // 分类名称
      categoryTree: [],
      selectedCategoryIds: [],

      // 总条数
      total: 0,

      paoductsListEcharts:[],

      //试图抽屉
      drawer:false,
      direction:'rtl',
      activeTab: 'quantity',

      // 图表实例
      categoryCountChart: null,    // 分类商品数量饼图
      categoryRatioChart: null,    // 分类商品占比饼图
    }
  },
  methods: {
    // 获得商品列表
    getlist() {
      this.loading = true;
      // 处理分类参数，确保传递给后端的是数组
      const params = {...this.queryParams};
      if (this.selectedCategoryIds && this.selectedCategoryIds.length > 0) {
        params.categoryIds = this.selectedCategoryIds;
      }
      console.log("获得商品列表 搜索参数",params)
      getlist(params).then(Response => {
        console.log("获得商品列表后端返回",Response)
        this.paoductsList = Response.rows
        this.total=Response.total
      }).catch(error => {
        console.error("获取商品列表失败:", error);
        this.loading = false;
      });
      // 初始化图表数据
      const param2 = {

          productName: "",
          categoryIds: [] ,
          pageNum: 1,
          pageSize: 100,
      };
      getlist(param2).then(Response => {
        //console.log("获得商品列表后端返回",Response)
        this.paoductsListEcharts = Response.rows
        this.total=Response.total
      }).catch(error => {
        console.error("获取商品列表失败:", error);
        this.loading = false;
      });
      this.loading = false
    },
    // 获得分类名称 用于搜索
    getCategoryName() {
      getCategoryName().then(Response => {
        console.log("获得后端返回的分类名称",Response)
        this.categoryTree = Response.data
      }).catch(error => {
        console.error("获取分类名称失败:", error);
      });

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getlist()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 处理分类选择变化
    handleCategoryChange(value) {
      // 将选中的分类ID赋值给查询参数
      this.selectedCategoryIds = value || [];
    },
    /** 导出按钮点击事件（完整实现） */
    handleExport() {
      // 1. 弹出确认框
      this.$confirm('确认导出当前筛选条件下的库存数据?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true; // 显示加载中（避免重复点击）
        // 处理分类参数，确保传递给后端的是数组
        const params = {...this.queryParams};
        if (this.selectedCategoryIds && this.selectedCategoryIds.length > 0) {
          params.categoryIds = this.selectedCategoryIds;
        }

        // 2. 发送请求（携带当前筛选条件，如商品名称、分类）
        return exportList({
          //productName: this.queryParams.productName, // 商品名称筛选
          // categoryIds: this.queryParams.categoryIds,     // 分类筛选
        });
      }).then(response => {
        console.log("导出按钮点击事件（完整实现）",response)
        // 3. 解析二进制流，创建下载链接
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // Excel文件类型
        });
        const url = URL.createObjectURL(blob); // 创建临时URL

        // 4. 触发下载
        const a = document.createElement('a'); // 创建<a>标签
        a.href = url;
        a.download = `库存数据_${new Date().getTime()}.xlsx`; // 文件名（带时间戳防重复）
        document.body.appendChild(a);
        a.click(); // 模拟点击下载

        // 5. 清理临时资源
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        this.$message.success('导出成功！');
      }).catch(error => {
        // 6. 错误处理（如无数据、网络异常）
        this.$message.error('导出失败，请重试');
      }).finally(() => {
        this.loading = false; // 关闭加载中
      });
    },
    //关闭视图抽屉
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    // 打开抽屉并初始化图表
    openDrawer() {
      this.drawer = true;
      this.$nextTick(() => {
        this.initCharts();
      });
    },
    // 初始化所有图表
    initCharts() {
      this.initCategoryCountChart();
      this.initCategoryRatioChart();
    },
    // 1. 初始化分类商品数量饼图
    initCategoryCountChart() {
      if (!this.categoryCountChart) {
        this.categoryCountChart = echarts.init(this.$refs.categoryCountChart);
      }

      // 统计每个分类的商品数量和库存总量
      const categoryDataMap = {};
      this.paoductsListEcharts.forEach(item => {
        if (!categoryDataMap[item.categoryName]) {
          categoryDataMap[item.categoryName] = {
            count: 0,          // 商品数量
            totalQuantity: 0   // 库存总量
          };
        }
        categoryDataMap[item.categoryName].count += 1;
        categoryDataMap[item.categoryName].totalQuantity += item.quantity;
      });

      // 转换为图表所需格式
      const chartData = Object.entries(categoryDataMap).map(([name, data]) => ({
        name,
        value: data.count,        // 饼图扇区大小基于商品数量
        totalQuantity: data.totalQuantity  // 附加库存总量数据
      }));

      const option = {
        title: { text: '分类商品数量分布', left: 'center' },
        tooltip: {
          trigger: 'item',
          // 自定义提示框内容，显示商品数量和库存总量
          formatter: (params) => {
            const { name, value, data } = params;
            return `${name}: <br/>商品数量: ${value} 件<br/>库存总量: ${data.totalQuantity} 个`;
          }
        },
        legend: { orient: 'vertical', left: 'left' },
        series: [{
          name: '分类商品统计',// 系列名称（会显示在图例和tooltip中）
          type: 'pie',         // 图表类型：饼图
          radius: '60%',         // 饼图半径（相对容器大小的百分比）
          data: chartData,          // 数据源：从分类统计结果转换来的数组
          emphasis: {
            itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }
          }
        }]
      };

      this.categoryCountChart.setOption(option);
    },

    // 2. 初始化分类商品占比饼图
    initCategoryRatioChart() {
      if (!this.categoryRatioChart) {
        this.categoryRatioChart = echarts.init(this.$refs.categoryRatioChart);
      }

      // 统计每个分类的商品总数占比
      const categoryTotalMap = {};
      const totalProducts = this.paoductsListEcharts.length;

      this.paoductsListEcharts.forEach(item => {
        categoryTotalMap[item.categoryName] = (categoryTotalMap[item.categoryName] || 0) + 1;
      });

      const option = {
        title: { text: '分类商品占比', left: 'center' },
        tooltip: { trigger: 'item', formatter: '{b}: {c}%' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{
          name: '占比',
          type: 'pie',
          radius: '60%',
          data: Object.entries(categoryTotalMap).map(([name, value]) => ({
            name,
            value: ((value / totalProducts) * 100).toFixed(2) // 计算百分比
          })),
          label: { formatter: '{b}: {c}%' },
          emphasis: {
            itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }
          }
        }]
      };

      this.categoryRatioChart.setOption(option);
    },
    // 销毁图表实例
    destroyCharts() {
      this.categoryCountChart?.dispose();
      this.categoryRatioChart?.dispose();
      this.categoryInventoryChart?.dispose();
      this.categoryCountChart = null;
      this.categoryRatioChart = null;
      this.categoryInventoryChart = null;
    }
    //测试分支









  },
  watch: {
    // 数据变化时更新图表
    paoductsListEcharts: {
      handler() {
        if (this.drawer) this.$nextTick(() => this.initCharts());
      },
      deep: true
    },
    // 抽屉关闭时销毁图表
    drawer(val) {
      if (!val) this.destroyCharts();
    }
  },
  beforeDestroy() {
    this.destroyCharts(); // 组件销毁时清理图表
  },
  created() {
    this.getlist()
    this.getCategoryName()
  },
}
</script>

<style scoped lang="scss">.no-image {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #c0c4cc;
  font-size: 24px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.image-slot i {
  font-size: 24px;
}
</style>
